import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt

mat = sio.loadmat('ex7faces.mat')
X = mat['X']
print(X.shape)
# (5000, 1024)

def plot_100_images(X):
    fig, axs = plt.subplots(ncols=10, nrows=10, figsize=(10, 10))
    for c in range(10):
        for r in range(10):
            axs[c, r].imshow(X[10*c + r].reshape(32, 32).T, cmap='Greys_r')  # 显示单通道的灰度图
            axs[c, r].set_xticks([])
            axs[c, r].set_yticks([])
    plt.show()


plot_100_images(X)

# 1、去均值化
means = np.mean(X, axis=0)
X_demean = X - means
C = X_demean.T @ X_demean  # X_demean 的协方差矩阵
U, S, V = np.linalg.svd(C)  # 特征向量

# 2、从特征向量中抽取前36列
U1 = U[:, :36]
X_reduction = X_demean @ U1 # 降维
print(X_reduction.shape)
# (5000, 36)

X_recover = X_reduction @ U1.T + means  # 重构图像
plot_100_images(X_recover)


